<?php
defined('BASEPATH') OR exit('No direct script access allowed');
/**
 * Created by PhpStorm.
 * User: shwy
 * Date: 2017/7/21
 * Time: 11:55
 * 统计分析管理
 */
class Statement extends MY_Controller
{
    public function __construct()
    {
        parent::__construct();
        $this->load->model('purchaseOrder_model');
        $this->load->model('returnOrder_model');
        $this->load->model('goods_model');
        $this->load->model('supplier_model');
        $this->load->model('project_model');
        $this->load->model('stockPut_model');
        $this->load->model('stockOut_model');
        $this->load->model('goodsCategory_model');

        $this->load->library('Excels');
    }

    // 采购订单统计报表
    public function order()
    {
 		$page_num = $this->config->item('fenye')['pageNum']; //每页的数据
        $start_position = 0; //初始数据
        $page = $this->input->get('page'); //获取页码数量
        if ($page) {
            $start_position = ($page - 1) * $page_num;
        }
		// get安全处理
		$type = $this->input->get('type') ? $this->input->get('type') : 'goods';

        $fields = 'id, supplier,goodsMessage,createTime,endTime,name,purchaseCode,status,source';
		$where  = ['status' => 5];
        // 读取采购进货单的goodsMessage数据。
        $data   = $this->purchaseOrder_model->paging($fields, $where, $page_num, $start_position);
		if ($data['total_num'] != 0) {
		// 若数据存在
			$count = $data['total_num'];
			unset($data['total_num']);
			
			foreach ($data as $k => $v) {
				// 格式化goodsMessage json字符串
                $data[$k]['goodsMessage'] = json_decode($data[$k]['goodsMessage'], true);
			}	

        	if ($type == 'goods') {
        	// type 是商品类型的  
        		             
                foreach ($data as $k => $v) {
                	foreach ($data[$k]['goodsMessage'] as $k1 => $v1) {
                		$data[$k]['goodsMessage'][$k1]['supplier'] = $data[$k]['supplier'];
                	}
				}				
//				dd($data);
                // 把格式化的字符串放入一个新数组中
                foreach ($data as $v2) {
                    foreach ($v2['goodsMessage'] as $v3) {
                        if (!$v3['price']) continue;
                        $new[] = $v3;
                    }
                }
//				dd($new);
                // 再根据product_no 相同，放入一个数组
                foreach ($new as $v4) {
                    $res[$v4['product_no']][] = $v4;
                }
//				dd($res);
                // 统计合计数量金和合计金额
                foreach ($res as $k5 => $v5) {
                    $new2[$k5]['quantity'] = array_sum(array_column($v5, 'quantity'));
                    $new2[$k5]['priceAll'] = number_format(array_sum(array_column($v5, 'priceAll')), 2);
                }
//				dd($new2);
                // 再根据新数组的key查询商品表
                foreach ($new2 as $k6 => $v6) {
                    $arg = [
                        'product_no' => $k6
                    ];					
					$goodsFields = 'id, ckId,product_no,name,source,one_category,supplier';
               
                    $goods[] = $this->goods_model->getByFieldQueryData($goodsFields, $arg);
                }
				dd($goods);
                $goods = array_filter($goods);
				// 2物料包、3书籍、4机器耗材、9打印机租赁、8供应商商品
                foreach ($goods as $k => $v) {
//                  $dataId = $v['ckId'] ? $v['ckId'] : $v['id'];
                    switch ($v['one_category']){
                        case 2:
                            $goods[$k]['one_category'] = "物料包";
                            break;
                        case 3:
                            $goods[$k]['one_category'] = "书籍";
                            break;
                        case 4:
                            $goods[$k]['one_category'] = "机器耗材";
                            break;
                        case 8:
                            $goods[$k]['one_category'] = "供应商商品";
                            break;
                        case 9:
                            $goods[$k]['one_category'] = "打印机租赁";
                            break;
                    }
                }	
//				dd($goods);
                foreach ($new2 as $k7 => $v7) {
                    foreach ($goods as $k8 => $v8) {
                        if ($k7 == $v8['product_no']) {
                            $goods[$k8]['quantity'] = $v7['quantity'];
                            $goods[$k8]['priceAll'] = $v7['priceAll'];
                        }
                    }
                }
//				dd($goods);
                foreach ($goods as $k9 => $v9) {
                    foreach ($res as $k10 => $v10) {
                        if ($v9['product_no'] == $k10) {
                            $goods[$k9]['specification222'] = $v10;
                            break;
                        } else {
                            $goods[$k9]['specification222'] = 5213;
                        }
                    }
                }
//				dd($goods);
                foreach ($goods as $k11 => $v11) {
                    foreach ($data as $v10) {
                        //TODO 加入到前端页面列表这里直接使用两个数组循环的数据加入参数。
                        $goods[$k11]['createTime'] = $v10['createTime'];
                        $goods[$k11]['endTime'] = $v10['endTime'];
                    }
                }
//				dd($goods);
                $viewData = [
                    'list' 		=> $goods,  	// 这里得到从数据库中的当页数据
                    'totalNum'  => $count, 	// 这里得到从数据库中的总页数
                ];
				
            } elseif ($type == 'gys') {
            // type 是按供应商的
	            foreach ($data as $k => $v) {
                $arg = [
                    'name' => $v['supplier']
                ];
                $supplier[] = $this->supplier_model->getByFieldQueryData('id,name,code,type,linkMan,address', $arg, 0);
            }

	            // 根据供应商相同整合数据
	            foreach ($data as $k2 => $v2) {
	                $res[$v2['supplier']][] = $v2;
	            }

	            foreach ($res as $k3 => $v3) {
	
	                // 预定义变量防止报错Undefined index：xxxx
	                $res[$k3]['quantity'] = [];
	                $res[$k3]['priceAll'] = [];
	
	                foreach ($v3 as $k4 => $v4) {
	                    // 查询总商品数量和采购金额
	                    $res[$k3]['quantity'][] .= array_sum(array_column($v4['goodsMessage'], 'quantity'));
	                    $res[$k3]['priceAll'][] .= array_sum(array_column($v4['goodsMessage'], 'priceAll'));
	                }
					
	                foreach ($supplier as $v5) {
	                    if ($k3 == $v5['name']) {
	                        $res[$k3]['code'] = $v5['code'];
	                        $res[$k3]['type'] = $v5['type'];
	                        $res[$k3]['supplierId'] = $v5['id'];
	                        $res[$k3]['linkMan'] = $v5['linkMan'];
	                        $res[$k3]['address'] = $v5['address'];
	                    }
	                }
	            }
				
	            // 删除多余数据
	            foreach ($res as $k6 => $v6) {
	                foreach ($v6 as $k7 => $v7) {
	                    if (is_numeric($k7)) {
	                        unset($res[$k6][$k7]);
	                    }
	                }
	            }

                $viewData = [
                    'gyslist'  => $res,  		// 这里得到从数据库中的当页数据
                    'totalNum' => count($res),  // 这里得到从数据库中的总页数
                ];
					
	        } elseif ($type == 'order') {
	        // type 是按照订单的列表页面
	            // 直接读取$data的数据进行返回
	            foreach ($data as $k2 => $v2) {
	                $data[$k2]['quantity'] = array_sum(array_column($v2['goodsMessage'], 'quantity'));
	                $data[$k2]['priceAll'] = array_sum(array_column($v2['goodsMessage'], 'priceAll'));	
	                unset($data[$k2]['goodsMessage']);
	            }

                $viewData = [
                    'orderlist' => $data,  		// 这里得到从数据库中的当页数据
                    'totalNum'  => $count	 	// 这里得到从数据库中的总页数
                ];	
	        } elseif ($type == 'project') {
//	        	dd($data);
	        // type 是按照订单的列表页面
	            foreach ($data as $k => $v) {	             	
	                $arg = [
	                    'name' => $v['source']
	                ];					
	                $project[] = $this->project_model->getByFieldQueryData('id,name,code,linkMan,createTime', $arg, 0);
	            }
				
//				dd($project);
				
	            foreach ($data as $k2 => $v2) {
	                $res[$v2['source']][] = $v2;
	            }
//				dd($res);			
	            foreach ($res as $k3 => $v3) {
	                //预定义变量防止报错Undefined index：xxxx
	                $res[$k3]['quantity'] = [];
	                $res[$k3]['priceAll'] = [];
	
	                foreach ($v3 as $k4 => $v4) {
	                    //查询总商品数量和采购金额
	                    $res[$k3]['quantity'][] .= array_sum(array_column($v4['goodsMessage'], 'quantity'));
	                    $res[$k3]['priceAll'][] .= array_sum(array_column($v4['goodsMessage'], 'priceAll'));
	                }

	                foreach ($project as $v5) {
	                    if ($k3 == $v5['name']) {
	                        $res[$k3]['code'] = $v5['code'];
	                        $res[$k3]['projectId'] = $v5['id'];
	                        $res[$k3]['linkMan'] = $v5['linkMan'];
	                        $res[$k3]['createTime'] = $v5['createTime'];
	                    }
	                }
	            }
	            //删除多余数据
	            foreach ($res as $k6 => $v6) {
	                foreach ($v6 as $k7 => $v7) {
	                    if (is_numeric($k7)) {
	                        unset($res[$k6][$k7]);
	                    }
	                }
	            }
//				dd($res);
	            $viewData = [
	                'projectlist' => $res,  		// 这里得到从数据库中的当页数据
	                'totalNum' 	  => count($res) 	// 这里得到从数据库中的总页数
	            ];				
	        }

			$viewData['pageNum'] = $page_num;	// 每页显示多少条
		} else {
		// 若数据不存在返回的结果
            $viewData = [
                'list' 		=> '',  	 // 这里得到从数据库中的当页数据
                'totalNum' 	=> 0, 		 // 这里得到从数据库中的总页数
                'pageNum' 	=> $page_num // 每页显示多少条
            ];
        }
        $this->load->view('/admin/statement/order/list', $viewData);					
    }

    // 供应商采购订单统计明细
    public function orderSupplierDetail()
    {
        $arg = [
            'id' => $_GET['supplierId']
        ];

        //根据 $_GET['supplierId'] 获取供应商id 查询对应供应商数据

        $data['list'] = $this->supplier_model->getByFieldQueryData('id,code,name,supplierUser,supplierPass,linkMan,phone,address', $arg, 0);

        //然后在查询，该供应商的信息，和下面的所有采购的商品（需求一个新增的方法）
        $arg2 = [
            'supplier' => $data['list']['name']
        ];
        $goodsMessage = $this->purchaseOrder_model->getByFieldQueryData('createTime,goodsMessage', $arg2, 1);

        foreach ($goodsMessage as $k => $v) {
            $goodsMessage[$k]['goodsMessage'] = json_decode($v['goodsMessage'], true);
        }

//        __format($goodsMessage);


        $arr = [];

        //数组中读个key，合并成一个数组循环方式修改。
        foreach($goodsMessage as $item) {

            $arr = array_merge($arr,(array)$item['createTime'],$item['goodsMessage']);

        }

//        __format($arr);

        //此方法是为了把时间加入到数组中
        foreach ($arr as $k2=>$v2){
            //如果不是数组，是时间错，就把内容加入到下一级的数组中，加入成功之后删除改数组
            if(!is_array($v2)){
                $arr[$k2+1]['time'] = $v2;

                unset($arr[$k2]);
            }
        }

        //此方法是为了让那些没有时间的加上上一级时间
        foreach ($arr as $k3=>$v3){
            if(!isset($v3['time'])){
                $arr[$k3]['time'] = $arr[$k3-1]['time'];
            }
        }

        $data['goodsMessage'] = $arr;




//        foreach ($goodsMessage as $item) {
//            foreach ($item['goodsMessage'] as $v) {
//                $data['goodsMessage'][] = $v;
//            }
//        }


//        __format($arr);
//        __format($data);


        $this->load->view('/admin/statement/order/supplierDetail', $data);


    }

    //项目采购订单统计明细
    public function orderProjectDetail()
    {

        //根据 $_GET['supplierId'] 获取供应商id
        //查询对应供应商数据

        //然后在查询，该供应商的信息，和下面的所有采购的商品（需求一个新增的方法）

        $arg = [
            'id' => $_GET['projectId']
        ];

        //根据 $_GET['supplierId'] 获取供应商id 查询对应供应商数据

        $data['list'] = $this->project_model->getByFieldQueryData('id,code,name,source,linkMan,note', $arg, 0);

        //然后在查询，该供应商的信息，和下面的所有采购的商品（需求一个新增的方法）
        $arg2 = [
            'source' => $data['list']['name']
        ];
        $goodsMessage = $this->purchaseOrder_model->getByFieldQueryData('goodsMessage', $arg2, 1);

        foreach ($goodsMessage as $k => $v) {
            $goodsMessage[$k]['goodsMessage'] = json_decode($v['goodsMessage'], true);
        }

        $arr = [];

        //数组中读个key，合并成一个数组循环方式修改。
        foreach($goodsMessage as $item) {

            $arr = array_merge($arr,$item['goodsMessage']);

        }

        $data['goodsMessage'] = $arr;


        $this->load->view('/admin/statement/order/projectDetail', $data);

    }

    // 采购质量统计报表根据供应商
    public function qualityBySupplier()
    {
        $page_num = $this->config->item('fenye')['pageNum'];
        $start_position = 0;
        $page = $this->input->get('page');
        if ($page) {
            $start_position = ($page - 1) * $page_num;
        }
        // 两个类型退货统计和换货统计
        $type = $this->input->get('type');
        $type = isset($type) ? $type : 'returnOrder';
		
		$fields = 'goodsMessage, supplier';
        // 根据状态不同，取得不同的数据
        if ($type == 'returnOrder') {
            $data = $this->returnOrder_model->getByFieldQueryData($fields, array('type' => '采购退货单'), 1);
//			dd($data);
            foreach ($data as $k => $v) {
                $data[$k]['goodsMessage'] = json_decode($data[$k]['goodsMessage'], true);
			    
                $supplier[] = $this->supplier_model->getByFieldQueryData('id, name, code, type', array('name' => $v['supplier']), 0);
            }
//			dd($supplier);
            //根据供应商相同整合数据，key使用供应商name当做
            foreach ($data as $k2 => $v2) {
                $res[$v2['supplier']][] = $v2;
            }
//			dd($res);
            foreach ($res as $k3 => $v3) {
                $res[$k3]['quantity'] = [];

                foreach ($v3 as $k4 => $v4) {
                    //查询总商品数量和采购金额
                    $res[$k3]['quantity'][] .= array_sum(array_column($v4['goodsMessage'], 'quantity'));
                }
				
                //因为k3 此时 == 供应商的name  然后和供应商的name判断
                foreach ($supplier as $v5) {
                    if ($k3 == $v5['name']) {
                        $res[$k3]['code'] = $v5['code'];
                        $res[$k3]['type'] = $v5['type'];
                        $res[$k3]['supplierId'] = $v5['id'];
                    }
                }
            }

            // 删除多余数据，就是删除key= 0，1，2的数据，因为需要的数据已经取出来了
            // 到此，退货单的数据已经完毕。
            foreach ($res as $k6 => $v6) {
                foreach ($v6 as $k7 => $v7) {
                    if (is_numeric($k7)) {
                        unset($res[$k6][$k7]);
                    }
                }
            }
//			dd($res);
            // 这里开始统计进货单的数据，主要是为了统计列表中 采购进货数量 字段
            // 以下的步骤就跟上面类似
            foreach ($res as $k8 => $v8) {
                $field2 = 'id,name,supplier,goodsMessage,createTime,endTime,name,purchaseCode,status,source,attribute';

                $purchaseOrder[] = $this->purchaseOrder_model->getByFieldQueryData($field2, array('supplier' => $k8, 'type' => '采购进货单'), 1);
            }
			$purchaseOrder = array_filter($purchaseOrder);
//			dd($purchaseOrder);
            // 循环进货单的数据，找出attribute(商品属性)字段， 种类/数量
            // 利用字符串技术，查出后面的数量字段，再用 供应商 名字当key
            foreach ($purchaseOrder as $k9=>$v9) {
                foreach ($v9 as $k10=>$v10){
                    $attribute[$v10['supplier']][] = substr($v10['attribute'],strpos($v10['attribute'],'/')+1,strlen($v10['attribute']));
                }
            }
//			dd($attribute);
            // 和 res数据比较key是否相同，相同则就加入
            foreach ($res as $k11=>$v11) {
                foreach ($attribute as $k12=>$v12) {
                    if($k11 == $k12){
                        $res[$k11]['purchaseNum'] = array_sum($v12);				
                    }
                }
            }
			
			foreach ($res as $k13 => $v13) {
				if (!isset($v13['purchaseNum'])) {
					$res[$k13]['purchaseNum'] = '无数据';
				}
			}
//			dd($res);
            if (isset($data) && $data) {
                $viewData = [
                    'thlist'   => $res,  //这里得到从数据库中的当页数据
                    'totalNum' => count($res), //这里得到从数据库中的总页数
                    'pageNum'  => $page_num //每页显示多少条
                ];
            } else {
                $viewData = [
                    'thlist' => '',  //这里得到从数据库中的当页数据
                    'totalNum' => 0, //这里得到从数据库中的总页数
                    'pageNum' => $page_num //每页显示多少条
                ];
            }
//			dd($viewData);
            $this->load->view('/admin/statement/quality/supplier', $viewData);


        } elseif ($type == 'barterOrder') {
        	
            $data = $this->returnOrder_model->getByFieldQueryData($fields, array('type' => '采购换货单'), 1);
			
            foreach ($data as $k => $v) {
                $data[$k]['goodsMessage'] = json_decode($data[$k]['goodsMessage'], true);
                $arg = [
                    'name' => $v['supplier']
                ];
                $supplier[] = $this->supplier_model->getByFieldQueryData('id,name,code,type', $arg, 0);
            }

            //根据供应商相同整合数据
            foreach ($data as $k2 => $v2) {
                $res[$v2['supplier']][] = $v2;
            }

            foreach ($res as $k3 => $v3) {

                //预定义变量防止报错Undefined index：xxxx
                $res[$k3]['quantity'] = [];


                foreach ($v3 as $k4 => $v4) {
                    //查询总商品数量和采购金额
                    $res[$k3]['quantity'][] .= array_sum(array_column($v4['goodsMessage'], 'quantity'));
                }

                foreach ($supplier as $v5) {
                    if ($k3 == $v5['name']) {
                        $res[$k3]['code'] = $v5['code'];
                        $res[$k3]['type'] = $v5['type'];
                        $res[$k3]['supplierId'] = $v5['id'];
                    }
                }
            }

            //删除多余数据，就是删除key= 0，1，2的数据，因为需要的数据已经取出来了
            //到此，退货单的数据已经完毕。
            foreach ($res as $k6 => $v6) {
                foreach ($v6 as $k7 => $v7) {
                    if (is_numeric($k7)) {
                        unset($res[$k6][$k7]);
                    }
                }

            }

//            __format($res);


            //这里开始统计进货单的数据，主要是为了统计列表中 采购进货数量 字段
            //一下的步骤就跟上面类似
            foreach ($res as $k8 => $v8) {
                $field2 = 'id,supplier,goodsMessage,createTime,endTime,name,purchaseCode,status,source,attribute';

                $arg2 = [
                    'supplier' => $k8
                ];

                $purchaseOrder[] = $this->purchaseOrder_model->getByFieldQueryData($field2, $arg2, 1);
            }

//            __format($purchaseOrder);
            //            __format($purchaseOrder);

            //循环进货单的数据，找出attribute字段， 种类/数量
            //利用字符串技术，查出后面的数量字段，再用 供应商 名字当key
            foreach ($purchaseOrder as $k9=>$v9){
                foreach ($v9 as $k10=>$v10){
                    // substr 最后一个参数不填，则表示到字符串结尾
                    $attribute[$v10['supplier']][] = substr($v10['attribute'],strpos($v10['attribute'],'/')+1);
//                    $attribute[$v10['supplier']][] = substr($v10['attribute'],strpos($v10['attribute'],'/')+1,strlen($v10['attribute']));
                }
            }

//            __format($attribute);



//            __format($res);

            // 和 res数据比较key是否相同，相同则就加入
            foreach ($res as $k11=>$v11){
                foreach ($attribute as $k12=>$v12){
                    if($k11 == $k12){
                        $res[$k11]['purchaseNum'] = array_sum($v12);
                    }
                }
            }

//            __format($res);
            if (isset($data) && $data) {
                $viewData = [
                    'hhlist' => $res,  //这里得到从数据库中的当页数据
                    'totalNum' => count($res), //这里得到从数据库中的总页数
                    'pageNum' => $page_num //每页显示多少条
                ];
            } else {
                $viewData = [
                    'hhlist' => '',  //这里得到从数据库中的当页数据
                    'totalNum' => 0, //这里得到从数据库中的总页数
                    'pageNum' => $page_num //每页显示多少条
                ];
            }


            $this->load->view('/admin/statement/quality/supplier', $viewData);

        }
    }

    // 采购质量统计报表 退换货 根据供应商 导出
    public function qualityBySupplierReturnDaoChu()
    {
        //两个类型退货统计和换货统计
        $type = isset($_GET['type']) ? $_GET['type'] : 'returnOrder';

        $field = '*';
        //根据状态不同，取得不同的数据
        if ($type == 'returnOrder') {
            $arg = [
                'type' => '采购退货单'
            ];
//            $data = $this->returnOrder_model->page('returnOrder', $arg, $page_num, $start_position, $field);
            $data[0] = $this->returnOrder_model->getByFieldQueryData($field, $arg, 1);

//            __format($data);

            foreach ($data[0] as $k => $v) {
                $data[0][$k]['goodsMessage'] = json_decode($data[0][$k]['goodsMessage'], true);


                $arg = [
                    'name' => $v['supplier']
                ];
                $supplier[] = $this->supplier_model->getByFieldQueryData('id,name,code,type', $arg, 0);
            }


//__format($supplier);
//            $res = array();
            //根据供应商相同整合数据，key使用供应商name当做
            foreach ($data[0] as $k2 => $v2) {
                $res[$v2['supplier']][] = $v2;
            }

//            __format($res);

            foreach ($res as $k3 => $v3) {

                //预定义变量防止报错Undefined index：xxxx
                $res[$k3]['quantity'] = [];

                foreach ($v3 as $k4 => $v4) {
                    //查询总商品数量和采购金额
                    $res[$k3]['quantity'][] .= array_sum(array_column($v4['goodsMessage'], 'quantity'));
                }
                //因为k3 此时 == 供应商的name  然后和供应商的name判断
                foreach ($supplier as $v5) {

                    if ($k3 == $v5['name']) {
                        $res[$k3]['code'] = $v5['code'];
                        $res[$k3]['type'] = $v5['type'];
                        $res[$k3]['supplierId'] = $v5['id'];
                    }
                }
            }

            //删除多余数据，就是删除key= 0，1，2的数据，因为需要的数据已经取出来了
            //到此，退货单的数据已经完毕。
            foreach ($res as $k6 => $v6) {
                foreach ($v6 as $k7 => $v7) {
                    if (is_numeric($k7)) {
                        unset($res[$k6][$k7]);
                    }
                }
            }

//            __format($res);

            //这里开始统计进货单的数据，主要是为了统计列表中 采购进货数量 字段
            //一下的步骤就跟上面类似
            foreach ($res as $k8 => $v8) {
                $field2 = 'id,name,supplier,goodsMessage,createTime,endTime,name,purchaseCode,status,source,attribute';

                $arg2 = [
                    'supplier' => $k8
                ];

                $purchaseOrder[] = $this->purchaseOrder_model->getByFieldQueryData($field2, $arg2, 1);
            }

//            __format($purchaseOrder);

            //循环进货单的数据，找出attribute字段， 种类/数量
            //利用字符串技术，查出后面的数量字段，再用 供应商 名字当key
            foreach ($purchaseOrder as $k9=>$v9){
                foreach ($v9 as $k10=>$v10){
                    $attribute[$v10['supplier']][] = substr($v10['attribute'],strpos($v10['attribute'],'/')+1,strlen($v10['attribute']));
                }
            }

//            __format($attribute);
            // 和 res数据比较key是否相同，相同则就加入
            foreach ($res as $k11=>$v11){
                foreach ($attribute as $k12=>$v12){
                    if($k11 == $k12){
                        $res[$k11]['purchaseNum'] = array_sum($v12);
                    }
                }
            }





        } elseif ($type == 'barterOrder') {
            $arg = [
                'type' => '采购换货单'
            ];
//            $data = $this->returnOrder_model->page('returnOrder', $arg, $page_num, $start_position, $field);
            $data[0] = $this->returnOrder_model->getByFieldQueryData($field, $arg, 1);

//           __format($data);

            foreach ($data[0] as $k => $v) {
                $data[0][$k]['goodsMessage'] = json_decode($data[0][$k]['goodsMessage'], true);


                $arg = [
                    'name' => $v['supplier']
                ];
                $supplier[] = $this->supplier_model->getByFieldQueryData('id,name,code,type', $arg, 0);
            }

//__format($supplier);
//            $res = array();
            //根据供应商相同整合数据
            foreach ($data[0] as $k2 => $v2) {
                $res[$v2['supplier']][] = $v2;
            }

            foreach ($res as $k3 => $v3) {

                //预定义变量防止报错Undefined index：xxxx
                $res[$k3]['quantity'] = [];


                foreach ($v3 as $k4 => $v4) {
                    //查询总商品数量和采购金额
                    $res[$k3]['quantity'][] .= array_sum(array_column($v4['goodsMessage'], 'quantity'));
                }

                foreach ($supplier as $v5) {
                    if ($k3 == $v5['name']) {
                        $res[$k3]['code'] = $v5['code'];
                        $res[$k3]['type'] = $v5['type'];
                        $res[$k3]['supplierId'] = $v5['id'];
                    }
                }
            }

            //删除多余数据，就是删除key= 0，1，2的数据，因为需要的数据已经取出来了
            //到此，退货单的数据已经完毕。
            foreach ($res as $k6 => $v6) {
                foreach ($v6 as $k7 => $v7) {
                    if (is_numeric($k7)) {
                        unset($res[$k6][$k7]);
                    }
                }

            }

//            __format($res);


            //这里开始统计进货单的数据，主要是为了统计列表中 采购进货数量 字段
            //一下的步骤就跟上面类似
            foreach ($res as $k8 => $v8) {
                $field2 = 'id,supplier,goodsMessage,createTime,endTime,name,purchaseCode,status,source,attribute';

                $arg2 = [
                    'supplier' => $k8
                ];

                $purchaseOrder[] = $this->purchaseOrder_model->getByFieldQueryData($field2, $arg2, 1);
            }

//            __format($purchaseOrder);
            //            __format($purchaseOrder);

            //循环进货单的数据，找出attribute字段， 种类/数量
            //利用字符串技术，查出后面的数量字段，再用 供应商 名字当key
            foreach ($purchaseOrder as $k9=>$v9){
                foreach ($v9 as $k10=>$v10){
                    // substr 最后一个参数不填，则表示到字符串结尾
                    $attribute[$v10['supplier']][] = substr($v10['attribute'],strpos($v10['attribute'],'/')+1);
//                    $attribute[$v10['supplier']][] = substr($v10['attribute'],strpos($v10['attribute'],'/')+1,strlen($v10['attribute']));
                }
            }

//            __format($attribute);



//            __format($res);

            // 和 res数据比较key是否相同，相同则就加入
            foreach ($res as $k11=>$v11){
                foreach ($attribute as $k12=>$v12){
                    if($k11 == $k12){
                        $res[$k11]['purchaseNum'] = array_sum($v12);
                    }
                }
            }


        }


        foreach ($res as $k13 =>$v13){
            $res[$k13]['quantity'] = array_sum($v13['quantity']);
            $res[$k13]['name'] = $k13;
            $res[$k13]['tuihuolv'] = round((array_sum($v13['quantity']) / $v13['purchaseNum']) * 100,2).'%';
//                round((array_sum($v2['quantity']) / $v2['purchaseNum']) * 100,2).'%'
        }



//            foreach ($res as $k14 =>$v14){
//            }

//            __format(array_values($res));

        if($type == 'returnOrder'){
            //表格标题字段名
            $title = [
                0 => [
                    1 => '退货商品数量',
                    2 => '供应商编码',
                    3 => '供应商类型',
                    4 => '序号',
                    5 => '采购商品数量',
                    6 => '供应商名称',
                    7 => '退货率',
                ],
            ];

        }else{
            //表格标题字段名
            $title = [
                0 => [
                    1 => '换货商品数量',
                    2 => '供应商编码',
                    3 => '供应商类型',
                    4 => '序号',
                    5 => '采购商品数量',
                    6 => '供应商名称',
                    7 => '退货率',
                ],
            ];
        }



//            __format($res);


        $this->excels->exports(array_values($res), $title);

    }

    //采购质量统计报表退货根据供应商的详情页面
    public function qualityBySupplierReturnDetails()
    {

        //读取stockOut和stockPut 两个表的数据
        $arg = [
            'id' => $_GET['supplierId']
        ];

        //根据 $_GET['supplierId'] 获取供应商id 查询对应供应商数据

        $data['list'] = $this->supplier_model->getByFieldQueryData('id,code,name,supplierUser,supplierPass,linkMan,phone,address', $arg, 0);

        //然后在查询，该供应商的信息，和下面的所有采购的商品（需求一个新增的方法）
        $arg2 = [
            'supplier' => $data['list']['name'],
            'type' => '采购退货单'
        ];

        $goodsMessage = $this->returnOrder_model->getByFieldQueryData('createTime,goodsMessage', $arg2, 1);

        foreach ($goodsMessage as $k => $v) {
            $goodsMessage[$k]['goodsMessage'] = json_decode($v['goodsMessage'], true);
        }

//        __format($goodsMessage);


        $arr = [];

        //数组中读个key，合并成一个数组循环方式修改。
        foreach($goodsMessage as $item) {

            $arr = array_merge($arr,(array)$item['createTime'],$item['goodsMessage']);

        }


        //此方法是为了把时间加入到数组中
        foreach ($arr as $k2=>$v2){
            //如果不是数组，是时间错，就把内容加入到下一级的数组中，加入成功之后删除改数组
            if(!is_array($v2)){
                $arr[$k2+1]['time'] = $v2;

                unset($arr[$k2]);
            }
        }

        //此方法是为了让那些没有时间的加上上一级时间
        foreach ($arr as $k3=>$v3){
            if(!isset($v3['time'])){
                $arr[$k3]['time'] = $arr[$k3-1]['time'];
            }
        }

//        __format($arr);


        $data['goodsMessage'] = $arr;


//        __format($data);


        $this->load->view('/admin/statement/quality/supplierReturnDetail', $data);



    }

    //采购质量统计报表换货根据供应商的详情页面
    public function qualityBySupplierBarterDetails()
    {

        //读取stockOut和stockPut 两个表的数据
        $arg = [
            'id' => $_GET['supplierId']
        ];

        //根据 $_GET['supplierId'] 获取供应商id 查询对应供应商数据

        $data['list'] = $this->supplier_model->getByFieldQueryData('id,code,name,supplierUser,supplierPass,linkMan,phone,address', $arg, 0);

        //然后在查询，该供应商的信息，和下面的所有采购的商品（需求一个新增的方法）
        $arg2 = [
            'supplier' => $data['list']['name'],
            'type' => '采购换货单'
        ];

        $goodsMessage = $this->returnOrder_model->getByFieldQueryData('createTime,goodsMessage', $arg2, 1);

        foreach ($goodsMessage as $k => $v) {
            $goodsMessage[$k]['goodsMessage'] = json_decode($v['goodsMessage'], true);
        }

//        __format($goodsMessage);


        $arr = [];

        //数组中读个key，合并成一个数组循环方式修改。
        foreach($goodsMessage as $item) {

            $arr = array_merge($arr,(array)$item['createTime'],$item['goodsMessage']);

        }


        //此方法是为了把时间加入到数组中
        foreach ($arr as $k2=>$v2){
            //如果不是数组，是时间错，就把内容加入到下一级的数组中，加入成功之后删除改数组
            if(!is_array($v2)){
                $arr[$k2+1]['time'] = $v2;

                unset($arr[$k2]);
            }
        }

        //此方法是为了让那些没有时间的加上上一级时间
        foreach ($arr as $k3=>$v3){
            if(!isset($v3['time'])){
                $arr[$k3]['time'] = $arr[$k3-1]['time'];
            }
        }

//        __format($arr);


        $data['goodsMessage'] = $arr;


//        __format($data);


        $this->load->view('/admin/statement/quality/supplierBarterDetail', $data);



    }

    // 采购质量统计报表根据商品
    public function qualityByGoods()
    {
        $page_num = $this->config->item('fenye')['pageNum']; // 每页的数据
        $start_position = 0; // 初始数据
        $page = ($this->input->get('page')); // 获取页码数量
        if ($page) {
        	$start_position = ($page - 1) * $page_num;
        }
		
		// 两个类型退货统计和换货统计
		$type = $this->input->get('type');
        $type = isset($type) ? $type : 'returnOrder';
        
        //根据状态不同，取得不同的数据
        if ($type == 'returnOrder') {
            $data = $this->returnOrder_model->paging($fields = 'goodsMessage', array('type' => '采购退货单'), $page_num, $start_position);
			
			if ($data['total_num'] != 0) {
				$totalNum = $data['total_num'];
				unset($data['total_num']);
				foreach ($data as $k => $v) {
	                $data[$k]['goodsMessage'] = json_decode($data[$k]['goodsMessage'], true);
	            }
	            // 把格式化的字符串放入一个新数组中
	            foreach ($data as $v2) {
	                foreach ($v2['goodsMessage'] as $v3) {
	                	if (!$v3['price']) continue;
	                    $new[] = $v3;
	                }
	            }
	
	            // 根据product_no 相同，放入一个数组
	            $res = array(); //想要的结果
	            foreach ($new as $v4) {
	                $res[$v4['product_no']][] = $v4;
	            }
				
	            // 采购退货单的商品数量
	            foreach ($res as $k5 => $v5) {
	                $new2[$k5]['quantity'] = array_sum(array_column($v5, 'quantity'));
	            }			
	//			dd($new2);
	            // 根据新数组的key查询商品表
	            foreach ($new2 as $k6 => $v6) {
	                $goods[] = $this->goods_model->getByFieldQueryData('id,ckId,product_no,name,source,one_category,supplier', array('product_no' => $k6), 0);
	            }
				
	            foreach ($new2 as $k7 => $v7) {
	                foreach ($goods as $k8 => $v8) {
	                    // 退货数量
	                    if ($k7 == $v8['product_no']) {
	                        $goods[$k8]['quantity'] = $v7['quantity'];
	                    }
	                }
	            }
				
	            // 这里开始读取采购进货单的所有数据，因为是根据商品来的，所以，可以读取所有商品的信息。
	            $purchaseOrderData = $this->purchaseOrder_model->getData($field = '*', 1);
				
	            foreach ($purchaseOrderData as $k9 => $v9) {
	                $purchaseOrderData[$k9]['goodsMessage'] = json_decode($purchaseOrderData[$k9]['goodsMessage'], true);
	            }
	
	            // 把格式化的字符串放入一个新数组中
	            foreach ($purchaseOrderData as $v10) {
	                foreach ($v10['goodsMessage'] as $v11) {
	                    $purchaseNew[] = $v11;
	                }
	            }
				
	            // 再根据product_no 相同，放入一个数组
	            $purchaseNewRes = array(); //想要的结果
	            foreach ($purchaseNew as $v12) {
	                $purchaseNewRes[$v12['product_no']][] = $v12;
	            }
	//			dd($purchaseNewRes);
	            // 采购退货单的商品数量
	            foreach ($purchaseNewRes as $k13 => $v13) {
	                $purchaseNew2[$k13]['quantity'] = array_sum(array_column($v13, 'quantity'));
	            }
				
	            foreach ($goods as $k15 => $v15) {
	                foreach ($purchaseNew2 as $k14 => $v14) {
	                    //TODO 这里有一个循环对比商品的product_no和进货单的key
	                    //TODO 如果加上else的话，所有循环数据都会被再次覆盖，所以，这里先去除else
	                    if ($k14 == $v15['product_no']) {
	                        $goods[$k15]['purchaseNum'] = $v14['quantity'];
	                    }
	                }
	            }
	        	$viewData = [
                        'thlist'   => $goods,    // 这里得到从数据库中的当页数据
                        'totalNum' => $totalNum, // 这里得到从数据库中的总页数
                        'pageNum'  => $page_num  // 每页显示多少条
                    ];
			} else {
				$viewData = [
                        'thlist'   => '',  //这里得到从数据库中的当页数据
                        'totalNum' => 0, //这里得到从数据库中的总页数
                        'pageNum'  => $page_num //每页显示多少条
                    ];
			}
                


            } elseif ($type == 'barterOrder') {
            $arg = ['type' => '采购换货单'];
            $data = $this->returnOrder_model->page('returnOrder', $arg, $page_num, $start_position, $field);

            foreach ($data[0] as $k => $v) {
                $data[0][$k]['goodsMessage'] = json_decode($data[0][$k]['goodsMessage'], true);
            }

//把格式化的字符串放入一个新数组中
            foreach ($data[0] as $v2) {
                foreach ($v2['goodsMessage'] as $v3) {
                    $new[] = $v3;
                }
            }


//在根据product_no 相同，放入一个数组
            $res = array(); //想要的结果
            foreach ($new as $v4) {
                $res[$v4['product_no']][] = $v4;
            }

//                echo '<pre>';
//                print_r($res);
//                die;

// 采购退货单的商品数量
            foreach ($res as $k5 => $v5) {
                $new2[$k5]['quantity'] = array_sum(array_column($v5, 'quantity'));
            }

//                __format($new2);


//在根据新数组的key查询商品表
            foreach ($new2 as $k6 => $v6) {
                $arg = [
                    'product_no' => $k6
                ];

                $goods[] = $this->goods_model->getByFieldQueryData('id,ckId,product_no,name,source,one_category,supplier', $arg, 0);
            }

            foreach ($new2 as $k7 => $v7) {
                foreach ($goods as $k8 => $v8) {
                    //退货数量
                    if ($k7 == $v8['product_no']) {
                        $goods[$k8]['quantity'] = $v7['quantity'];
                    }

                }
            }


            $purchaseOrderData = $this->purchaseOrder_model->page('purchaseOrder', 0, $page_num, $start_position, $field);
            // 这里开始读取采购进货单的所有数据，因为是根据商品来的，所以，可以读取所有商品的信息。
            $purchaseOrderData[0] = $this->purchaseOrder_model->getData($field,1);

//            __format($purchaseOrderData);
//            __format($purchaseOrderData);


            foreach ($purchaseOrderData[0] as $k9 => $v9) {
                $purchaseOrderData[0][$k9]['goodsMessage'] = json_decode($purchaseOrderData[0][$k9]['goodsMessage'], true);
            }

            //把格式化的字符串放入一个新数组中
            foreach ($purchaseOrderData[0] as $v10) {
                foreach ($v10['goodsMessage'] as $v11) {
                    $purchaseNew[] = $v11;
                }
            }


            //在根据product_no 相同，放入一个数组
            $purchaseNewRes = array(); //想要的结果
            foreach ($purchaseNew as $v12) {
                $purchaseNewRes[$v12['product_no']][] = $v12;
            }

//                echo '<pre>';
//                print_r($res);
//                die;

            // 采购退货单的商品数量
            foreach ($purchaseNewRes as $k13 => $v13) {
                $purchaseNew2[$k13]['quantity'] = array_sum(array_column($v13, 'quantity'));
            }

//            __format($purchaseNew2);


            foreach ($goods as $k15 => $v15) {
                foreach ($purchaseNew2 as $k14 => $v14) {

                    //TODO 这里有一个循环对比商品的product_no和进货单的key
                    //TODO 如果加上else的话，所有循环数据都会被再次覆盖，所以，这里先去除else

                    if ($k14 == $v15['product_no']) {

                        $goods[$k15]['purchaseNum'] = $v14['quantity'];
                    }
                }
            }

            if (isset($data[0]) && $data[0]) {
                $viewData = [
                    'hhlist' => $goods,  //这里得到从数据库中的当页数据
                    'totalNum' => $data['total_num'], //这里得到从数据库中的总页数
                    'pageNum' => $page_num //每页显示多少条
                ];
            } else {
                $viewData = [
                    'hhlist' => '',  //这里得到从数据库中的当页数据
                    'totalNum' => 0, //这里得到从数据库中的总页数
                    'pageNum' => $page_num //每页显示多少条
                ];
            }
        }
		$this->load->view('/admin/statement/quality/goods', $viewData);
    }

    //出入库统计报表根据商品
    public function outAndPutByGoods()
    {

        //读取stockOut和stockPut 两个表的数据
        $page_num = $this->config->item('fenye')['pageNum']; //每页的数据
        $start_position = ''; //初始数据
        $page = ($this->input->get('page')); //获取页码数量
        if (!$page) {
            $num = 1;
            $start_position = ($num - 1) * $page_num;
        } else {
            $start_position = ($page - 1) * $page_num;
        }

        $type = isset($_GET['type']) ? $_GET['type'] : 'put';

        //读取采购进货单的goodMessage数据。

        if ($type == 'put') {
//            if(!$data[0]){
//                redirect('/home/error');
//            }
//            $data = $this->stockPut_model->page('stockPut', 0, $page_num, $start_position, '*');
            $data[0] = $this->stockPut_model->getData('*',  1);


        }else if ($type == 'out'){

//            $data = $this->stockOut_model->page('stockOut', 0, $page_num, $start_position, '*');

            $data[0] = $this->stockOut_model->getData('*',  1);

        }


//      if(!$data[0]){
//          redirect('/home/error');
//      }

//        __format($data);



        // if(!$data[0]){
        //     redirect('/home/error');
        // }

//        __format($data);


        if ($data[0]) {
//                __format($data);
            //格式化goodsMessage json字符串
            foreach ($data[0] as $k => $v) {
                $data[0][$k]['goodsMessage'] = json_decode($data[0][$k]['goodsMessage'], true);
            }

            //把格式化的字符串放入一个新数组中
            foreach ($data[0] as $v2) {
                foreach ($v2['goodsMessage'] as $v3) {
                    $new[] = $v3;
                }
            }

            // 再根据product_no 相同，放入一个数组
            $res = array(); //想要的结果
            foreach ($new as $v4) {
                $res[$v4['product_no']][] = $v4;
            }

            //统计合计数量金和合计金额
            foreach ($res as $k5 => $v5) {
                $new2[$k5]['quantity'] = array_sum(array_column($v5, 'quantity'));
                $new2[$k5]['priceAll'] = array_sum(array_column($v5, 'priceAll'));

//                $new2[$k5]['createTime'] = $v5['createTime'];
//                    foreach ($v5 as $k9 => $v9) {
//                        if (__checkTrue($v9['order']) && $k5==) {
//                            $new2[$k5]['isSpecification'] = $res;
//                            break;
//                        } else {
//                            $new2[$k5]['isSpecification'] = 0;
//                        }
//                    }
//
            }

//                __format($new2);


            //在根据新数组的key查询商品表
            foreach ($new2 as $k6 => $v6) {
                $arg = [
                    'product_no' => $k6
                ];

                $goods[] = $this->goods_model->getByFieldQueryData('id,ckId,product_no,name,source,one_category,supplier', $arg, 0);
            }
			
			$goods = array_filter($goods);
			
            foreach ($new2 as $k7 => $v7) {
                foreach ($goods as $k8 => $v8) {

                    if ($k7 == $v8['product_no']) {
                        $goods[$k8]['quantity'] = $v7['quantity'];
                        $goods[$k8]['priceAll'] = $v7['priceAll'];
                    }
                }
            }

        }

        if($type == 'put'){
            $viewData = [
                'putlist' => $goods,  //这里得到从数据库中的当页数据
                'pageNum' => $page_num //每页显示多少条
            ];
        }elseif($type == 'out') {
            $viewData = [
                'outlist' => $goods,  //这里得到从数据库中的当页数据
//                'totalNum' => 0, //这里得到从数据库中的总页数
                'pageNum' => $page_num //每页显示多少条
            ];
        }

        $this->load->view('/admin/statement/warehouse/goods', $viewData);
    }

    //出入库统计报表根据商品入库的详情页面
    public function outAndPutByGoodsPutDetails()
    {

        //读取stockOut和stockPut 两个表的数据
        $arg = [
            'id' => $_GET['goodsId']
        ];

        //根据 $_GET['supplierId'] 获取供应商id 查询对应供应商数据

        $field = 'id,product_no,name,goodsUnit,jbarcode,supplier,price,is_can_size';
        $data['list'] = $this->goods_model->getByFieldQueryData('*', $arg, 0);

        //根据第一个id查询数据
        $arg = [
            'level' => 2,
            'one_category' => $data['list']['one_category']
        ];
        //查询二级名字
        $twoData = $this->goodsCategory_model->getByFieldQueryData('id,name', $arg, 1);

        $arg = [
            'level' => 3,
            'parent_id' => $data['list']['two_category']
        ];
        //查询询三级名字
        $threeData = $this->goodsCategory_model->getByFieldQueryData('id,name', $arg, 1);

        $data['list']['two_category_name'] = $twoData;
        $data['list']['three_category_name'] = $threeData;

        //然后在查询，该供应商的信息，和下面的所有采购的商品（需求一个新增的方法）

//        __format($data);

        $goodsMessage = $this->stockPut_model->getData('*', 1);

        foreach ($goodsMessage as $k => $v) {
            $goodsMessage[$k]['goodsMessage'] = json_decode($v['goodsMessage'], true);
        }

//        __format($goodsMessage);


        $arr = [];

        //数组中读个key，合并成一个数组循环方式修改。
        foreach($goodsMessage as $item) {

            $arr = array_merge($arr,(array)$item['createTime'],$item['goodsMessage']);

        }


        //此方法是为了把时间加入到数组中
        foreach ($arr as $k2=>$v2){
            //如果不是数组，是时间错，就把内容加入到下一级的数组中，加入成功之后删除改数组
            if(!is_array($v2)){
                $arr[$k2+1]['time'] = $v2;

                unset($arr[$k2]);
            }
        }

        //此方法是为了让那些没有时间的加上上一级时间
        foreach ($arr as $k3=>$v3){
            if(!isset($v3['time'])){
                $arr[$k3]['time'] = $arr[$k3-1]['time'];
            }
        }

//        __format($arr);


        $data['goodsMessage'] = $arr;

        foreach ($data['goodsMessage'] as $k5=>$v5){
            if($v5['product_no'] != $data['list']['product_no']){
                unset($data['goodsMessage'][$k5]);
            }
        }


//        __format($data);


        $this->load->view('/admin/statement/warehouse/goodsPutDetail', $data);



    }

    //出入库统计报表根据商品出库的详情页面
    public function outAndPutByGoodsOutDetails()
    {

        //读取stockOut和stockPut 两个表的数据
        $arg = [
            'id' => $_GET['goodsId']
        ];

        //根据 $_GET['supplierId'] 获取供应商id 查询对应供应商数据

        $field = 'id,product_no,name,goodsUnit,jbarcode,supplier,price,is_can_size';
        $data['list'] = $this->goods_model->getByFieldQueryData('*', $arg, 0);

        //根据第一个id查询数据
        $arg = [
            'level' => 2,
            'one_category' => $data['list']['one_category']
        ];
        //查询二级名字
        $twoData = $this->goodsCategory_model->getByFieldQueryData('id,name', $arg, 1);

        $arg = [
            'level' => 3,
            'parent_id' => $data['list']['two_category']
        ];
        //查询询三级名字
        $threeData = $this->goodsCategory_model->getByFieldQueryData('id,name', $arg, 1);

        $data['list']['two_category_name'] = $twoData;
        $data['list']['three_category_name'] = $threeData;

        //然后在查询，该供应商的信息，和下面的所有采购的商品（需求一个新增的方法）

//        __format($data);

        $goodsMessage = $this->stockOut_model->getData('*', 1);

        foreach ($goodsMessage as $k => $v) {
            $goodsMessage[$k]['goodsMessage'] = json_decode($v['goodsMessage'], true);
        }

//        __format($goodsMessage);


        $arr = [];

        //数组中读个key，合并成一个数组循环方式修改。
        foreach($goodsMessage as $item) {

            $arr = array_merge($arr,(array)$item['createTime'],$item['goodsMessage']);

        }


        //此方法是为了把时间加入到数组中
        foreach ($arr as $k2=>$v2){
            //如果不是数组，是时间错，就把内容加入到下一级的数组中，加入成功之后删除改数组
            if(!is_array($v2)){
                $arr[$k2+1]['time'] = $v2;

                unset($arr[$k2]);
            }
        }

        //此方法是为了让那些没有时间的加上上一级时间
        foreach ($arr as $k3=>$v3){
            if(!isset($v3['time'])){
                $arr[$k3]['time'] = $arr[$k3-1]['time'];
            }
        }

//        __format($arr);


        $data['goodsMessage'] = $arr;

        foreach ($data['goodsMessage'] as $k5=>$v5){
            if($v5['product_no'] != $data['list']['product_no']){
                unset($data['goodsMessage'][$k5]);
            }
        }


//        __format($data);


        $this->load->view('/admin/statement/warehouse/goodsOutDetail', $data);
    }

    //出入库统计报表根据供应商统计
    public function outAndPutBySupplier()
    {

        //读取stockOut和stockPut 两个表的数据
        //读取stockOut和stockPut 两个表的数据
        $page_num = $this->config->item('fenye')['pageNum']; //每页的数据
        $start_position = ''; //初始数据
        $page = ($this->input->get('page')); //获取页码数量
        if (!$page) {
            $num = 1;
            $start_position = ($num - 1) * $page_num;
        } else {
            $start_position = ($page - 1) * $page_num;
        }

        $type = isset($_GET['type']) ? $_GET['type'] : 'put';

        //读取采购进货单的goodMessage数据。

        if ($type == 'put') {
//            if(!$data[0]){
//                redirect('/home/error');
//            }
//            $data = $this->stockPut_model->page('stockPut', 0, $page_num, $start_position, '*');
            $data[0] = $this->stockPut_model->getData('*', 1);

        }else if ($type == 'out'){

//            $data = $this->stockOut_model->page('stockOut', 0, $page_num, $start_position, '*');
            $data[0] = $this->stockOut_model->getData('*', 1);

        }

//        __format($data);



//      if(!$data[0]){
//          redirect('/home/error');
//      }

        // if(!$data[0]){
        //     redirect('/home/error');
        // }


        if ($data[0]) {

            foreach ($data[0] as $k => $v) {
                $data[0][$k]['goodsMessage'] = json_decode($data[0][$k]['goodsMessage'], true);


                $arg = [
                    'name' => $v['supplier']
                ];
                $supplier[] = $this->supplier_model->getByFieldQueryData('id,name,code,type,linkMan,address', $arg, 0);
            }

//            __format($supplier);

            //根据供应商相同整合数据
            foreach ($data[0] as $k2 => $v2) {
                $res[$v2['supplier']][] = $v2;
            }

//            __format($res);
            foreach ($res as $k3 => $v3) {

                //预定义变量防止报错Undefined index：xxxx
                $res[$k3]['quantity'] = [];
                $res[$k3]['priceAll'] = [];

                foreach ($v3 as $k4 => $v4) {
                    //查询总商品数量和采购金额
                    $res[$k3]['quantity'][] .= array_sum(array_column($v4['goodsMessage'], 'quantity'));
                    $res[$k3]['priceAll'][] .= array_sum(array_column($v4['goodsMessage'], 'priceAll'));

                    $res[$k3]['createMan'] = $v4['createMan'];

                }

                foreach ($supplier as $v5) {
                    if($v5){
                        if ($k3 == $v5['name']) {
                            $res[$k3]['code'] = $v5['code'];
                            $res[$k3]['type'] = $v5['type'];
                            $res[$k3]['supplierId'] = $v5['id'];
                            $res[$k3]['linkMan'] = $v5['linkMan'];
                        }
                    }

                }
            }


            //删除多余数据
            foreach ($res as $k6 => $v6) {
                foreach ($v6 as $k7 => $v7) {
                    if (is_numeric($k7)) {
                        unset($res[$k6][$k7]);
                    }
                }

            }



        }

//        __format($res);


        if($type == 'put'){
            $viewData = [
                'putlist' => $res,  //这里得到从数据库中的当页数据
//                'totalNum' => $data['total_num'], //这里得到从数据库中的总页数
                'totalNum' => count($res), //这里得到从数据库中的总页数
                'pageNum' => $page_num //每页显示多少条
            ];
        }elseif($type == 'out') {
            $viewData = [
                'outlist' => $res,  //这里得到从数据库中的当页数据
                'totalNum' => 0, //这里得到从数据库中的总页数
                'pageNum' => $page_num //每页显示多少条
            ];
        }

//        __format($viewData);
        $this->load->view('/admin/statement/warehouse/supplier', $viewData);

    }

    //出入库统计报表根据供应商入库的详情页面
    public function outAndPutBySupplierPutDetails()
    {

        //读取stockOut和stockPut 两个表的数据
        $arg = [
            'id' => $_GET['supplierId']
        ];

        //根据 $_GET['supplierId'] 获取供应商id 查询对应供应商数据

        $data['list'] = $this->supplier_model->getByFieldQueryData('id,code,name,supplierUser,supplierPass,linkMan,phone,address', $arg, 0);

        //然后在查询，该供应商的信息，和下面的所有采购的商品（需求一个新增的方法）
        $arg2 = [
            'supplier' => $data['list']['name']
        ];
        $goodsMessage = $this->stockPut_model->getByFieldQueryData('createTime,goodsMessage', $arg2, 1);

        foreach ($goodsMessage as $k => $v) {
            $goodsMessage[$k]['goodsMessage'] = json_decode($v['goodsMessage'], true);
        }

//        __format($goodsMessage);


        $arr = [];

        //数组中读个key，合并成一个数组循环方式修改。
        foreach($goodsMessage as $item) {

            $arr = array_merge($arr,(array)$item['createTime'],$item['goodsMessage']);

        }


        //此方法是为了把时间加入到数组中
        foreach ($arr as $k2=>$v2){
            //如果不是数组，是时间错，就把内容加入到下一级的数组中，加入成功之后删除改数组
            if(!is_array($v2)){
                $arr[$k2+1]['time'] = $v2;

                unset($arr[$k2]);
            }
        }

        //此方法是为了让那些没有时间的加上上一级时间
        foreach ($arr as $k3=>$v3){
            if(!isset($v3['time'])){
                $arr[$k3]['time'] = $arr[$k3-1]['time'];
            }
        }

//        __format($arr);


        $data['goodsMessage'] = $arr;


//        __format($data);


        $this->load->view('/admin/statement/warehouse/supplierPutDetail', $data);



    }

    //出入库统计报表根据供应商出库的详情页面
    public function outAndPutBySupplierOutDetails()
    {

        //读取stockOut和stockPut 两个表的数据
        $arg = [
            'id' => $_GET['supplierId']
        ];

        //根据 $_GET['supplierId'] 获取供应商id 查询对应供应商数据

        $data['list'] = $this->supplier_model->getByFieldQueryData('id,code,name,supplierUser,supplierPass,linkMan,phone,address', $arg, 0);

        //然后在查询，该供应商的信息，和下面的所有采购的商品（需求一个新增的方法）
        $arg2 = [
            'supplier' => $data['list']['name']
        ];
        $goodsMessage = $this->stockOut_model->getByFieldQueryData('goodsMessage', $arg2, 1);

        foreach ($goodsMessage as $k => $v) {
            $goodsMessage[$k]['goodsMessage'] = json_decode($v['goodsMessage'], true);
        }

//        __format($goodsMessage);


        $arr = [];

        //数组中读个key，合并成一个数组循环方式修改。
        foreach($goodsMessage as $item) {

            $arr = array_merge($arr,$item['goodsMessage']);

        }

        $data['goodsMessage'] = $arr;


//        __format($data);


        $this->load->view('/admin/statement/warehouse/supplierOutDetail', $data);


    }

    //出入库统计报表根据项目统计
    public function outAndPutByProject()
    {


        //读取stockOut和stockPut 两个表的数据
        //按照订单的列表页面, 根据项目筛选
        $page_num = $this->config->item('fenye')['pageNum']; //每页的数据
        $start_position = ''; //初始数据
        $page = ($this->input->get('page')); //获取页码数量
        if (!$page) {
            $num = 1;
            $start_position = ($num - 1) * $page_num;
        } else {
            $start_position = ($page - 1) * $page_num;
        }

        $type = isset($_GET['type']) ? $_GET['type'] : 'put';

        //读取采购进货单的goodMessage数据。

        if ($type == 'put') {
//            if(!$data[0]){
//                redirect('/home/error');
//            }
//            $data = $this->stockPut_model->page('stockPut', 0, $page_num, $start_position, '*');
            $data[0] = $this->stockPut_model->getData('*',1);

        }else if ($type == 'out'){

//            $data = $this->stockOut_model->page('stockOut', 0, $page_num, $start_position, '*');
            $data[0] = $this->stockOut_model->getData('*',1);

        }
//        __format($data);

        //TODO 有问题,第二页无法翻页

//      if(!$data[0]){
//          redirect('/home/error');
//      }

        // if(!$data[0]){
        //     redirect('/home/error');
        // }


        foreach ($data[0] as $k => $v) {
            $data[0][$k]['goodsMessage'] = json_decode($data[0][$k]['goodsMessage'], true);

            $arg = [
                'name' => $v['source']
            ];
            $project[] = $this->project_model->getByFieldQueryData('id,name,source,code,linkMan,createTime', $arg, 0);
        }

//        __format($project);

//        print_r($project);die;

        foreach ($data[0] as $k2 => $v2) {
            $res[$v2['source']][] = $v2;
        }

//        __format($res);

        foreach ($res as $k3 => $v3) {



            //预定义变量防止报错Undefined index：xxxx
            $res[$k3]['quantity'] = [];
            $res[$k3]['priceAll'] = [];

            foreach ($v3 as $k4 => $v4) {
                //查询总商品数量和采购金额
                $res[$k3]['quantity'][] .= array_sum(array_column($v4['goodsMessage'], 'quantity'));
                $res[$k3]['priceAll'][] .= array_sum(array_column($v4['goodsMessage'], 'priceAll'));

                //出入库单据创建人员
                $res[$k3]['createMan'] = $v4['createMan'];
                $res[$k3]['source'] = $v4['source'];


            }

            foreach ($project as $v5) {
                if ($k3 == $v5['name']) {
                    $res[$k3]['code'] = $v5['code'];
                    $res[$k3]['projectId'] = $v5['id'];
                    $res[$k3]['linkMan'] = $v5['linkMan'];
                    $res[$k3]['createTime'] = $v5['createTime'];
                    $res[$k3]['projectsource'] = $v5['source'];
                }
            }
        }


        //删除多余数据
        foreach ($res as $k6 => $v6) {
            foreach ($v6 as $k7 => $v7) {
                if (is_numeric($k7)) {
                    unset($res[$k6][$k7]);
                }
            }

        }

//        __format($res);

        //这里使用项目联系人，linkMna
        //因为，这里的 项目名称== 项目来源。

        if($type == 'put'){
            $viewData = [
                'putlist' => $res,  //这里得到从数据库中的当页数据
//                'totalNum' => $data['total_num'], //这里得到从数据库中的总页数
                'totalNum' => count($res), //这里得到从数据库中的总页数
                'pageNum' => $page_num //每页显示多少条
            ];
        }elseif($type == 'out') {
            $viewData = [
                'outlist' => $res,  //这里得到从数据库中的当页数据
                'totalNum' => count($res), //这里得到从数据库中的总页数
                'pageNum' => $page_num //每页显示多少条
            ];
        }

//        __format($viewData);

        $this->load->view('/admin/statement/warehouse/project', $viewData);




    }

    //出入库统计报表根据项目入库的详情页面
    public function outAndPutByProjectPutDetails()
    {

        //根据 $_GET['supplierId'] 获取供应商id
        //查询对应供应商数据

        //然后在查询，该供应商的信息，和下面的所有采购的商品（需求一个新增的方法）

        $arg = [
            'id' => $_GET['projectId']
        ];

        //根据 $_GET['supplierId'] 获取供应商id 查询对应供应商数据

        $data['list'] = $this->project_model->getByFieldQueryData('id,code,name,source,linkMan,note', $arg, 0);

        //然后在查询，该供应商的信息，和下面的所有采购的商品（需求一个新增的方法）
        $arg2 = [
            'source' => $data['list']['name']
        ];
        $goodsMessage = $this->stockPut_model->getByFieldQueryData('goodsMessage', $arg2, 1);

        foreach ($goodsMessage as $k => $v) {
            $goodsMessage[$k]['goodsMessage'] = json_decode($v['goodsMessage'], true);
        }

        $arr = [];

        //数组中读个key，合并成一个数组循环方式修改。
        foreach($goodsMessage as $item) {

            $arr = array_merge($arr,$item['goodsMessage']);

        }

        $data['goodsMessage'] = $arr;


        $this->load->view('/admin/statement/warehouse/ProjectPutDetail', $data);




    }

    //出入库统计报表根据项目出库的详情页面
    public function outAndPutByProjectOutDetails()
    {

        //根据 $_GET['supplierId'] 获取供应商id
        //查询对应供应商数据

        //然后在查询，该供应商的信息，和下面的所有采购的商品（需求一个新增的方法）

        $arg = [
            'id' => $_GET['projectId']
        ];

        //根据 $_GET['supplierId'] 获取供应商id 查询对应供应商数据

        $data['list'] = $this->project_model->getByFieldQueryData('id,code,name,source,linkMan,note', $arg, 0);

        //然后在查询，该供应商的信息，和下面的所有采购的商品（需求一个新增的方法）
        $arg2 = [
            'source' => $data['list']['name']
        ];
        $goodsMessage = $this->stockOut_model->getByFieldQueryData('goodsMessage', $arg2, 1);

        foreach ($goodsMessage as $k => $v) {
            $goodsMessage[$k]['goodsMessage'] = json_decode($v['goodsMessage'], true);
        }

        $arr = [];

        //数组中读个key，合并成一个数组循环方式修改。
        foreach($goodsMessage as $item) {

            $arr = array_merge($arr,$item['goodsMessage']);

        }

        $data['goodsMessage'] = $arr;


        $this->load->view('/admin/statement/warehouse/ProjectOutDetail', $data);




    }


//TODO 看到时候需不需要出入库统计汇总
        public function warehouse()
        {


            $page_num = $this->config->item('fenye')['pageNum']; //每页的数据
            $start_position = ''; //初始数据
            $page = ($this->input->get('page')); //获取页码数量
            if (!$page) {
                $num = 1;
                $start_position = ($num - 1) * $page_num;
            } else {
                $start_position = ($page - 1) * $page_num;
            }

            $type = isset($_GET['type']) ? $_GET['type'] : 'goods';

            //读取采购进货单的goodMessage数据。
            if ($type == 'goods') {
                $data = $this->returnOrder_model->page('returnOrder', 0, $page_num, $start_position);

//            if(!$data[0]){
//                redirect('/home/error');
//            }
                if ($data[0]) {
//                __format($data);
                    //格式化goodsMessage json字符串
                    foreach ($data[0] as $k => $v) {
                        $data[0][$k]['goodsMessage'] = json_decode($data[0][$k]['goodsMessage'], true);
                    }

                    //把格式化的字符串放入一个新数组中
                    foreach ($data[0] as $v2) {
                        foreach ($v2['goodsMessage'] as $v3) {
                            $new[] = $v3;
                        }
                    }

                    //在根据product_no 相同，放入一个数组
                    $res = array(); //想要的结果
                    foreach ($new as $v4) {
                        $res[$v4['product_no']][] = $v4;
                    }

                    //统计合计数量金和合计金额
                    foreach ($res as $k5 => $v5) {
                        $new2[$k5]['quantity'] = array_sum(array_column($v5, 'quantity'));
                        $new2[$k5]['priceAll'] = array_sum(array_column($v5, 'priceAll'));
                        foreach ($v5 as $k9 => $v9) {
                            if (__checkTrue($v9['order']) && __checkTrue($v9['specification'])) {
                                $new2[$k5]['isSpecification'] = 1;
                                break;
                            } else {
                                $new2[$k5]['isSpecification'] = 0;
                            }
                        }
//
                    }

                    //在根据新数组的key查询商品表
                    foreach ($new2 as $k6 => $v6) {
                        $arg = [
                            'product_no' => $k6
                        ];

                        $goods[] = $this->goods_model->getByFieldQueryData('id,ckId,product_no,name,source,one_category', $arg, 0);
                    }

                    foreach ($new2 as $k7 => $v7) {
                        foreach ($goods as $k8 => $v8) {

                            if ($k7 == $v8['product_no']) {
                                $goods[$k8]['quantity'] = $v7['quantity'];
                                $goods[$k8]['priceAll'] = $v7['priceAll'];
                                $goods[$k8]['isSpecification'] = $v7['isSpecification'];
                            }

                        }
                    }

//                __format($goods);

                    $data[0] = $goods;
                    $viewData = [
                        'list' => $data[0],  //这里得到从数据库中的当页数据
                        'totalNum' => $data['total_num'], //这里得到从数据库中的总页数
                        'pageNum' => $page_num //每页显示多少条
                    ];
                } else {
                    $viewData = [
                        'list' => '',  //这里得到从数据库中的当页数据
                        'totalNum' => 0, //这里得到从数据库中的总页数
                        'pageNum' => $page_num //每页显示多少条
                    ];
                }

                $this->load->view('/admin/statement/warehouse', $viewData);

            } else {


                if (isset($data[0]) && $data[0]) {
                    $viewData = [
                        'gyslist' => $data[0],  //这里得到从数据库中的当页数据
                        'totalNum' => $data['total_num'], //这里得到从数据库中的总页数
                        'pageNum' => $page_num //每页显示多少条
                    ];
                } else {
                    $viewData = [
                        'gyslist' => '',  //这里得到从数据库中的当页数据
                        'totalNum' => 0, //这里得到从数据库中的总页数
                        'pageNum' => $page_num //每页显示多少条
                    ];
                }


                $this->load->view('/admin/statement/warehouse', $viewData);
            }

//        __format($data[0]);

//


        }


    }




































